﻿using System;
using Crevice2D.Core.Managers;
using Microsoft.Xna.Framework;

namespace Crevice2D.Core.Data
{
    public class Camera2D
    {
        public Vector2 Position { get; set; }
        public float Rotation { get; set; }
        public Vector2 Origin { get; set; }
        public float Zoom { get; set; }
        public double RadiusSquared { get; set; }

        protected Vector2 _origin;
        protected Matrix _transformMatrix;

        public Camera2D() { }

        public void Initialize()
        {
            Zoom = 1.0f;
            Rotation = 0.0f;

            _origin = new Vector2(RenderManager.Viewport.Bounds.Width / 2, RenderManager.Viewport.Bounds.Height / 2);
            RadiusSquared = Math.Pow(Math.Min(_origin.X, _origin.Y) / 4, 2);
        }

        public Matrix TransfromMatrix
        {
            get
            {
                _transformMatrix = Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, .0f)) *
                        Matrix.CreateRotationZ(Rotation) *
                        Matrix.CreateScale(Zoom, Zoom, 1.0f) *
                        Matrix.CreateTranslation(new Vector3(_origin.X, _origin.Y, .0f));
                return _transformMatrix;
            }
        }

        public void UpdatePosition(Vector2 pos, Vector2 prevPos)
        {
            if ((_origin - Vector2.Transform(pos, _transformMatrix)).LengthSquared() > RadiusSquared)
            {
                Position += (pos - prevPos);
            }
        }
    }
}